package org.linlinjava.litemall.admin.shiro;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.druid.util.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.linlinjava.litemall.db.domain.LitemallToken;
import org.linlinjava.litemall.db.service.LitemallTokenService;
import org.linlinjava.litemall.db.util.SpringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

public class AdminWebSessionManager extends DefaultWebSessionManager {

    public static final String LOGIN_TOKEN_KEY = "X-Litemall-Admin-Token";
    private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

    @Override
    protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
        String id = WebUtils.toHttp(request).getHeader(LOGIN_TOKEN_KEY);
            if (!StringUtils.isEmpty(id)) {
            //判断token是否失效 是否被挤下线
            /*LitemallTokenService litemallTokenService = (LitemallTokenService) SpringUtils.getBean("litemallTokenService");
            LitemallToken litemallToken = litemallTokenService.getOne(Wrappers.lambdaQuery(LitemallToken.class)
                    .eq(LitemallToken::getToken, id));
            //失效token已经被清除
            if(ObjectUtil.isNull(litemallToken)){
                return null;
            }
            //账号被挤下线或者被系统禁用
            if(litemallToken.getValid()==1||litemallToken.getValid()==2){
                litemallTokenService.removeById(litemallToken);
                //优化后需要主动向前端推送消息「提醒他已经被踢下线，并且刷新页面」
                return null;
            }*/
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, id);
            request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
            return id;
        } else {
            return super.getSessionId(request, response);
        }
    }
}
